<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ActivityTime_Controlers
 *
 * @author Samuel
 */
defined('BASEPATH') or die('forbidden');

class ActivityTime_Controller extends Controller {

    private $inc;
    private $activityList; //活动集合
    private $activityTypeList;
    private $tmpconnect;

    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        $this->inc = $this->config['inc'];

        $area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';

        if ($area_host == '') {
        	echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
        	return;
        }
        
        $area_host = $_SESSION['area_selected_host'];
        // 得到选择的区号
        $areanum = $_SESSION ['area_selected_id'];
        
        $this->tmpconnect = getTmpDbConnect (PLATFORM_ALL, 'all', $areanum, DBTYPE_DYNAMIC );
        
        // 活动对应表在dynamic_activity_map中
        $sql = "SELECT *  FROM dynamic_activity_map ";
        $this->db->query ( $sql );
        while ( $n = $this->db->get_array ( 'default' ) ) {
        	// print_r($n);
        	// exit();
        	if ($n['activityid'] > 1000 && $n['activityid'] < 1300) //需要配置礼包的活动
        	{
        		$this->activityTypeList [$n ['activityid']] ['activityid'] = $n ['activityid'];
        		$this->activityTypeList [$n ['activityid']] ['activityname'] = $n ['activityname'];
        		$this->activityTypeList [$n ['activityid']] ['activitytable'] = $n ['activitytable'];
        		$this->activityTypeList [$n ['activityid']] ['displayview'] = $n ['displayview'];
        		$this->activityTypeList [$n ['activityid']] ['messageid'] = $n ['messageid'];
        	}
        }

        $strResult = vpost($area_host . "action=10");
        $row = json_decode($strResult, true);

        foreach ($row as $key => $value) {
        	if ($value['activityId'] > 1000) //过滤礼包数据
        	{
            	$this->activityList[$value['activityId']] = $value['activityId'] . "-" . $value['name'];
        	}
        }
        //print_r($this->activityList,true);
    }

    function index() {
        //$area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
        //if ($area_host == '') {
        //   echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
        //}

        $this->view->display("activity/activitytime/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

        $area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
        //echo " area_host:$area_host ";
        //exit();
        $strResult = vpost($area_host . "action=10");

        $row = json_decode($strResult, true);

        foreach ($row as $key => $value) {
            if ($value['activityId'] > 1000) //过滤礼包数据 
            {
            	$value['startTime'] = get_datetime($value['startTime']);
            	$value['endTime'] = get_datetime($value['endTime']);
            	$value['isOpen'] = $value['isOpen'] == 1 ? translate('OPEN') : "<label style='color:#999999'>" . translate('CLOSE') . "</label>";
            	$value['defaultstate'] = $value['defaultstate'] == 1 ? translate('YES') : translate('NO');
            	$value['isEver'] = $this->inc['activity_isever'][$value['isEver']];
            	$value['activity_type'] = $this->inc['activity_type'][$value['activity_type']];
            	$rows[] = array('id' => $value['Id'], 'cell' => $value);
            }
        }

        //$this->view->assign("activityList",self::$activityList);	//把列表传过去

        $total = count($rows);
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );

        echo json_encode($result);

        //print_r($this->activityList);
        //exit();
    }

    function add() {
        set_time_limit(30);

        if (is_submit()) {
            $rowdata = $_POST['row'];
            //var_dump($rowdata);
            //exit();
            $area_host = $_SESSION['area_selected_host'];
            unset($rowdata['area_host']);
            $rowdata["start_time"] = strtotime($rowdata["start_time"]);
            $rowdata["end_time"] = strtotime($rowdata["end_time"]);
            $str = array_to_stringparam($rowdata);
            $str = $area_host . $str . "action=35";

            $strResult = vpost($str);

            $result = 0;
            //操作失败或者连接失败
            if ($strResult != '0' || $strResult === FALSE) {
                echo " get server data error ";
                $result = 1;
            } 
            else 
            {
            	//得到当前活动的最大subid
            	$strResult = vpost($area_host . "action=10");
            	
            	$row = json_decode($strResult, true);
            	$targetsubid = 0;
            	foreach ($row as $key => $value) {
            		if ($value['activityId'] == $rowdata['activity_id'])
            		{
            			if ($value['subid'] > $targetsubid)
            			{
            				$targetsubid = $value['subid'];
            			}
            		}
            	}
            	
            	//添加进数据库中
            	$tmptable = $this->activityTypeList[$rowdata['activity_id']]['activitytable'];
            	$tablerows = array();
            	$tmpsql1 = "SELECT * FROM $tmptable";
            	$this->tmpconnect->query($tmpsql1);
            	while($row = $this->tmpconnect->get_array())
            	{
            		$tablerows[] = $row;
            	}
            	//此表中是否有subid
            	$flag = false;
            	$newsubid = 0;
            	$tablemaxrow = array();
            	if (isset($tablerows[1]['subid']))
            	{
            		$flag = true;
            		//有就找出最大的subid
            		for ($i = 0; $i < count($tablerows); $i++)
            		{
            			if ($tablerows[$i]['subid'] > $newsubid)
            			{
            				$newsubid = $tablerows[$i]['subid'];
            			}
            		}
            		//加一层容错
            		if ($newsubid == $targetsubid)
            		{
            			$flag = false;
            		}
            		//用一个新数组存最大的subid的数据
            		for($i = 0; $i < count ( $tablerows ); $i ++) 
            		{
						if ($tablerows [$i] ['subid'] == $newsubid) 
						{
							$tablerows [$i] ['subid'] = $newsubid + 1;
							unset ( $tablerows [$i] ['id'] );
							$tablemaxrow [] = $tablerows [$i];
							// $tablemaxrow[]['subid'] = $newsubid + 1;
						}
					}
            	}
            	//插入数据库中
            	if ($flag && isset($tablemaxrow) && $newsubid != 0)
            	{
            		for ($i = 0; $i < count($tablemaxrow); $i++)
            		{
            			$this->tmpconnect->insert($tmptable, $tablemaxrow[$i]);
            		}
            	}
            	//通知游戏服重整表
            	$url = $area_host . "action=51&messageid=" . $rowdata['activity_id'];
            	$ret = vpost ( $url, 10 );
            	
                insert_log(translate('MENU_ACTIVITY_ACTIVITYTIME'),translate('ADD'), NULL, array("name" => $area_host . ' activity: ' . $rowdata['activity_id']));
            }
            cp_tips($result == 0 ? "success" : "error");
        }
        //var_dump($this->activityList); 
        $this->view->assign("activityList", $this->activityList); //把列表传过去        
        $this->view->display("activity/activitytime/add");
    }

    function edit($id = 0) {
        if (is_submit()) {
            $rowdata = $_POST['row'];
            $areaIds = $_POST['areaIds'];
            //var_dump($rowdata);
            //var_dump($areaIds);
            //var_dump($_POST);
            //exit(0);
            
            if ($rowdata['activityId'] == '1016' || $rowdata['activityId'] == '1017' || 
            		$rowdata['activityId'] == '1018' || $rowdata['activityId'] == '1014')  //根据轮数修改时间
            {
            	if (isset($rowdata['round']))
            	{
            		$rowdata['startTime'] = strtotime($rowdata['startTime']) - $rowdata['dayreset'] * 86400 * ($rowdata['round'] - 1);
            		$rowdata['endTime'] = strtotime($rowdata['endTime']) - $rowdata['dayreset'] * 86400 * ($rowdata['round'] - 1);
            	}
            }
            else
            {
            	$rowdata['startTime'] = strtotime($rowdata['startTime']);
            	$rowdata['endTime'] = strtotime($rowdata['endTime']);
            }
            /*if ($_POST['Operate'] == 0) {
                $area_host = get_area_list_url();
                $area_live_list = get_area_list_live();
                foreach ($area_live_list as $k => $w) {  //echo $k."***";
                    $strResult = vpost($area_host[$k] . array_to_stringparam($rowdata) . "action=11&id={$id}", 2);
                }
            } else if ($_POST['Operate'] == 1) {
            	$area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
                //echo $area_host . array_to_stringparam($rowdata) . "action=11&id={$id}";exit(0);
                $strResult = vpost($area_host . array_to_stringparam($rowdata) . "action=11&id={$id}", 2);
            }*/
            $area_host = get_area_list_url();
            $area_live_list = get_area_list_live();
            $areastr = "";
            if (in_array('0', $areaIds))
            {
            	foreach ($area_live_list as $k => $w) {  //echo $k."***";
            		$strResult = vpost($area_host[$k] . array_to_stringparam($rowdata) . "action=11&id={$id}", 2);
            		$areastr .= $k.',';
            	}
            }
            else
            {
            	foreach ($areaIds as $k => $v)
            	{
            		if (isset($area_live_list[$v]))
            		{
            			$strResult = vpost($area_host[$v].array_to_stringparam($rowdata) . "action=11&id={$id}", 2);
            			$areastr .= $v.',';
            		}
            	}
            }

            $result = 0;
            if ($strResult === FALSE || $strResult != '0') {
                $result = 1;
            }
            //echo $area_host . array_to_stringparam($rowdata) . "action=11&id={$id}";
            $areastr = substr($areastr, 0, -1);
            insert_log(translate('MENU_ACTIVITY_ACTIVITYTIME'),translate('EDIT'), NULL, array("info" => 'area: ' . $areastr . ',' . ' activity: ' . $rowdata['activityId']));
            cp_tips($result == 0 ? "success" : "error");
        }
        $area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
        $strResult = vpost($area_host . "action=10&id={$id}");
        $row = json_decode($strResult, true);
        /* echo $area_host . "action=10&id={$id}"."<br>";
          print_r($row); */
        //print_r($row);
        //echo "++++";
        //print_r($this->inc['activity_isever']);
        //print_r($this->inc['activity_isever'][$row[0]['isEver']]);
        //exit(0);
        $areanum = $_SESSION ['area_selected_id'];
        set_area_list_view("arealist", array($areanum));
        $this->view->assign("row", $row[0]);
        $this->view->assign("isEver", $this->form->select("row[isEver]", $this->inc['activity_isever'], $row[0]['isEver'], array('id' => 'isEver')));
        $this->view->display("activity/activitytime/edit");
    }

    function copyToOther($ids = 0) {
    	print_r($_POST);
    	echo " $ids = $ids ";
        if (is_submit()) {
        	/*
            $rowdata = $_POST['row'];

            $rowdata['startTime'] = strtotime($rowdata['startTime']);
            $rowdata['endTime'] = strtotime($rowdata['endTime']);
            if ($_POST['Operate'] == 0) {
                $area_host = get_area_list_url();
                $area_live_list = get_area_list_live();
                foreach ($area_live_list as $k => $w) {  //echo $k."***";
                    $strResult = vpost($area_host[$k] . array_to_stringparam($rowdata) . "action=11&id={$id}", 2);
                }
            } else if ($_POST['Operate'] == 1) {
                $area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
                //echo $area_host . array_to_stringparam($rowdata) . "action=11&id={$id}";exit;
                $strResult = vpost($area_host . array_to_stringparam($rowdata) . "action=11&id={$id}", 2);
            }

            $result = 0;
            if ($strResult === FALSE || $strResult != '0') {
                $result = 1;
            }
            //echo $area_host . array_to_stringparam($rowdata) . "action=11&id={$id}";
            cp_tips($result == 0 ? "success" : "error");
            */
        }
        //$area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
        //$strResult = vpost($area_host . "action=10&id={$ids}");
        //$row = json_decode($strResult, true);
        /* echo $area_host . "action=10&id={$id}"."<br>";
          print_r($row); */
        $this->view->assign("ids",json_decode($ids));
        $this->view->assign("row", $row[0]);
        $this->view->display("activity/activitytime/copy");
    }
    
    function del($id = 0)
    {
    	$c = 0;
    	$r = '';
    	if ($id === 0)
    		json_output($c, translate('C_INVALID_PARAM_ID', $id));
    	
    	$area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
    	//print_r($area_host."action=11&id={$id}");
    	//exit();
    	
    	//通过id获得活动id和subid，再通过活动id获得动态表名，最后删掉动态表中所有此subid的字段
    	$strResult = vpost($area_host . "action=10");
    	$row = json_decode($strResult, true);
    	$tmpactivityid = 0;
    	$tmpsubid = 0;
    	//var_dump($row);
    	foreach ($row as $key => $value)
    	{
    		if ($value['Id'] == $id)
    		{
    			$tmpactivityid = $value['activityId'];
    			$tmpsubid = $value['subid'];
    			break;
    		}
    	}
    	//var_dump($tmpactivityid);
    	//var_dump($tmpsubid);
    	if ($tmpsubid != 0)
    	{
    		if ($tmpsubid == 1)
    		{
    			//echo "<script>alert('Can not delete activity which subid = 1!!!');</script>";
    			$r = "Can not delete activity which subid = 1!!!";
    			json_output($c, $r);
    			return;
    		}
    	}
    	
    	$strResult = vpost($area_host . "action=55&id={$id}", 2);
    	
    	if ($strResult === "0")
    	{
    		$c = 1;
    		if ($tmpsubid != 0)
    		{
    			$tmptable = $this->activityTypeList[$tmpactivityid]['activitytable'];
    			//是否有subid
    			$tmpsql = "SELECT * FROM $tmptable";
    			$row = $this->tmpconnect->one($tmpsql);
    			if (isset($row['subid']))
    			{
    				$sql = "DELETE FROM $tmptable WHERE subid = $tmpsubid";
    				//var_dump($sql);
    				//exit(0);
    				$this->tmpconnect->execute($sql);
    			}
    		}
    		$url = $area_host . "action=51&messageid=" . $rowdata['activity_id'];
    		$ret = vpost ( $url, 10 );
    		insert_log(translate('MENU_ACTIVITY_ACTIVITYTIME'),translate('DEL'), array('id'=> $id));
    	}
    	else
    	{
    		$r = translate('C_TIPS_ERROR_TEXT');
    	}
    	json_output($c, $r);
    }

}

?>
